<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商品名称">
                <a-input allow-clear placeholder="请输入商品名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品分类">
                <a-select placeholder="请选择商品分类" v-model="queryParam.cat_id" allowClear>
                  <a-select-option v-for="item of catList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item>
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 已上架 </a-radio-button>
          <a-radio-button value="0"> 已下架 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="$router.push({ path: '/serviceHome/goodsEdit' })">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="updateAll('status', 1)">批量上架</a-menu-item>
              <a-menu-item @click="updateAll('status', 0)">批量下架</a-menu-item>
              <a-menu-item @click="updateAll('is_delete', 1)">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-alert type="info" show-icon style="margin: 10px 0" v-if="selectedRowKeys.length">
        <span slot="message">
          已选择 <span style="color: red">{{ selectedRowKeys.length }}</span> 项
        </span>
      </a-alert>

      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="{
          current: queryParam.pageNo,
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :rowSelection="{
          selectedRowKeys: this.selectedRowKeys,
          onChange: (e) => {
            this.selectedRowKeys = e
          },
        }"
        :columns="columns"
        :data-source="list"
        :scroll="{ x: 'max-content' }"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.cover_pic" alt="" />
            </div>
            <div class="info">
              <span>{{ record.name }}</span>
              <span>{{ getCatText(record.cat) }}</span>
            </div>
          </div>
        </div>

        <span slot="price" slot-scope="text"> ￥{{ text || 0 }} </span>

        <span slot="virtual_sales" slot-scope="text"> {{ text || 0 }} </span>

        <div slot="status" slot-scope="text, scope">
          <a-switch
            checked-children="上架"
            un-checked-children="下架"
            :checked="scope.status == 1"
            @click="(e) => changeStatus(e, scope)"
          />
        </div>

        <div slot="action" slot-scope="scope">
          <a-button type="link" size="small" @click="handle('edit', scope, false)">编辑</a-button>

          <a-divider type="vertical" style="margin: 0 1px" />

          <a-dropdown>
            <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多 <a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handel('change', scope, 2)">删除</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handle('code', scope)">小程序二维码</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handle('edit', goods.id, true)">复制商品</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handle('copy', scope)">复制小程序链接</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </a-table>
    </a-card>

    <a-modal title="小程序二维码" :visible="showQrCode" @ok="showQrCode = false" @cancel="showQrCode = false">
      <div style="display: flex; justify-content: center">
        <img style="width: 300px; height: 300px" :src="this.qrcodeUrl" alt="" />
      </div>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { goodsCatList } from '@/api/marketing/serviceHome'
import { list as goodsList, status as changeGoodStatus, updateAll as updateAllApi } from '@/api/goods/goods'
import { getQr } from '@/api/goods/goods'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
  },
  {
    title: '商品名称',
    scopedSlots: {
      customRender: 'name',
    },
    width: 300,
  },
  {
    title: '售价',
    dataIndex: 'price',
    scopedSlots: {
      customRender: 'price',
    },
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: '虚拟销量',
    dataIndex: 'virtual_sales',
    scopedSlots: {
      customRender: 'virtual_sales',
    },
    sorter: (a, b) => a.virtual_sales - b.virtual_sales,
  },
  {
    title: '上下架',
    scopedSlots: {
      customRender: 'status',
    },
  },

  {
    title: '操作',
    width: 130,
    scopedSlots: {
      customRender: 'action',
    },
    fixed: 'right',
  },
]

export default {
  computed: {
    getCatText() {
      return (cat) => {
        if (cat && cat.length) {
          return cat.map((el) => el.name).join('/')
        } else {
          return '-'
        }
      }
    },
  },

  data() {
    return {
      // 搜索参数
      queryParam: {
        pageNo: 1,
        limit: 10,
        name: '',
        status: '-1',
        cat_id: '',
        product_type: 6,
      },

      selectedRowKeys: [],
      columns,
      list: [],
      catList: [],

      qrcodeUrl: '',
      showQrCode: false,
    }
  },

  created() {
    if (this.$route.meta.queryParam) {
      this.queryParam = this.$route.meta.queryParam
    }

    this.getList()
    this.getCatList()
  },

  beforeRouteLeave(to, from, next) {
    from.meta.queryParam = this.queryParam
    next()
  },

  filters: {
    sku(e) {
      return '-'
    },

    orderStatus(val) {
      if (val == 0) {
        return 'background-color:#faad14;'
      }

      if (val == 1) {
        return 'background-color:#faad14;'
      }

      if (val == 2) {
        return 'background-color:#65c817;'
      }
    },
  },

  methods: {
    updateAll(type, status) {
      if (!this.selectedRowKeys.length) {
        this.$message.warn('请先勾选商品')
        return
      }

      // if (type === 'price') {
      //   this.showPrice = true
      //   return
      // }

      var text = '删除'
      if (type === 'status') {
        text = status === 1 ? '上架' : '下架'
      } else if (type === 'quick_purchase') {
        text = status === 1 ? '加入快速购买' : '关闭快速购买'
      }
      this.$confirm({
        title: '是否批量' + text + '?',
        onOk: () => {
          updateAllApi({
            type: type,
            status: status,
            goods_id: this.selectedRowKeys,
          }).then((res) => {
            if (res.code === 0) {
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          })
        },
        onCancel() {},
      })
    },

    handle(type, item, parmas) {
      switch (type) {
        case 'code':
          this.showQscode(item.id)
          break

        case 'change':
          this.changeStatus(parmas, item)
          break

        case 'copy':
          this.copyUrl(item.id)
          break

        case 'edit':
          this.$router.push({ path: `/serviceHome/goodsEdit?id=${item.id}&isCopy=${parmas}` })
          break

        default:
          break
      }
    },

    getCatList() {
      goodsCatList().then((res) => {
        this.catList = res.data.list
      })
    },

    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },

    // 获取数据
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      const res = await goodsList(this.queryParam)
      if (res.code == 0) {
        this.list = res.data.data
        this.totalCount = res.data.totalCount
      }
      hide()
    },

    // 切换商品上下架删除状态
    async changeStatus(e, scope) {
      let status

      switch (e) {
        case true:
          status = 1
          break

        case false:
          status = 0
          break

        default:
          status = e
          break
      }

      const res = await changeGoodStatus({ id: scope.id, status })
      if (res.code == 0) {
        this.getList()
      }
    },

    showQscode(id) {
      const h = this.$createElement
      this.$message.loading({ content: '请求中...', key: 'qrcodeLoading' })
      getQr({
        id,
        is_worker: 1,
      })
        .then((res) => {
          if (res.code === 0) {
            const qrcodeUrl = res.data.qr_url

            this.showQrCode = true
            this.qrcodeUrl = qrcodeUrl
          } else {
            this.$message.error(res.msg)
          }
        })
        .then(() => {
          this.$message.destroy()
        })
    },

    copyUrl(id) {
      this.$copyText(`goods/goods/goods?id=${id}`).then(
        () => {
          this.$message.success('复制成功！')
        },
        () => {
          this.$message.error('复制成功！')
        }
      )
    },
  },
}
</script>
<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    margin-top: 11px;
    display: flex;
    align-items: center;
    margin-right: 15px;
  }
  .ant-btn {
    margin-top: 11px;
  }
}
.tip {
  line-height: normal;
  margin-bottom: 0;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}

.tagBox {
  display: flex;
  align-items: center;
}

.tag {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
}
</style>
